<!doctype html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JS028-学生就业信息表案例</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
</head>
<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        background-color: #222;
        color: snow;
    }

    input[type="number"]::-webkit-outer-spin-button,
    input[type="number"]::-webkit-inner-spin-button {
        -webkit-appearance: none !important;
        margin: 0;
    }

    input[type="number"] {
        -moz-appearance: textfield;
    }

    .container {
        max-width: 60rem;
        margin: 1rem;
        padding: 1rem;
        border: 1px solid silver;

        overflow-y: auto;
        scrollbar-color: dimgray #333;

        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: start;
        gap: 1rem;
    }

    ul li {
        margin-left: 1rem;
    }

    form.create-row label {
        display: flex;
        align-items: center;
        justify-content: start;
        flex-wrap: wrap;
        gap: .5rem;

        text-wrap: nowrap;

        > * {
            height: 2rem;
            border: none;
            font-size: 1rem;
        }

        input, select, button {
            border-radius: .2rem;
        }

        input {
            width: 8rem;
            padding-left: .5rem;
            background-color: #333;
            color: snow;

            &::placeholder {
                color: darkgray;
            }

            &.age {
                width: 4rem;
            }

            &.salary {
                width: 6rem;
            }
        }

        select {
            padding: 0 .5rem;
            background-color: #333;
            color: snow;
        }

        button.submit {
            padding: 0 1rem;
            background-color: lightgreen;
            cursor: pointer;
        }
    }

    button.debug-submit {
        height: 2rem;
        padding: 0 1rem;
        border: none;
        border-radius: .2rem;
        background-color: crimson;
        cursor: pointer;

        text-wrap: nowrap;
        font-size: 1rem;
        color: snow;
    }

    .row-count {
        width: 100%;
        padding: .8rem 1rem;
        text-align: right;
        color: darkgray;
        background-color: #333;

        span {
            margin: 0 .2rem;
            color: coral;
        }
    }

    table {
        width: 100%;
        overflow-y: auto;
        border-collapse: collapse;
        text-wrap: nowrap;

        tr {
            transition: background-color 100ms;
        }

        th, td {
            padding: .5rem 1rem;
            text-align: center;
            border: 1px solid gray;
        }

        th {
            background-color: #333;
        }

        td.operations {
            position: relative;

            .delete-row {
                position: absolute;
                inset: 0;
                display: flex;
                align-items: center;
                justify-content: center;

                border: none;
                background-color: crimson;
                cursor: pointer;

                font-size: .9rem;
                color: snow;

                &:active {
                    background-color: darkred;
                    color: darkgray;
                }
            }
        }
    }
</style>
<body>

<div class="container">
    <h1>JS028-学生就业信息表案例</h1>
    <div class="abstract">
        <ul>
            <li>增删数据，且学号独立递增（不受删除影响）</li>
            <li>本地存储，同一浏览器数据不丢失</li>
        </ul>
    </div>
    <form class="create-row" action="">
        <label>
            <input class="uname" type="text" placeholder="姓名">
            <input class="age" type="number" min="18" max="200" placeholder="年龄">
            <input class="salary" type="number" min="0" placeholder="薪资">
            <select name="gender" id="gender">
                <option value="男">男</option>
                <option value="女">女</option>
            </select>
            <select name="city" id="city">
                <option value="北京">北京</option>
                <option value="上海">上海</option>
                <option value="广州">广州</option>
                <option value="深圳">深圳</option>
                <option value="曹县">曹县</option>
                <option value="理塘">理塘</option>
                <option value="合肥">合肥</option>
            </select>
            <button class="submit"><i class="fa-solid fa-circle-plus"></i>提交</button>
        </label>
    </form>
    <button class="debug-submit"><i class="fa-solid fa-circle-plus"></i>提交2条假数据(debug)</button>
    <div class="row-count">共<span>0</span>条数据</div>
    <table>
        <thead>
        <tr>
            <th>学号</th>
            <th>用户名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>薪资</th>
            <th>就业城市</th>
            <th>录入时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

<script>
    let stusData;
    let globalNewStuId = localStorage.getItem('global-new-stu-id') || 1;
    const tableBodyEl = document.querySelector('table tbody');
    const rowCountEl = document.querySelector('.row-count span');

    (function initDebugBtnEl() {
        document.querySelector('button.debug-submit').addEventListener('click', () => {
            stusData.push({
                id: globalNewStuId++, uname: 'pink', age: 22, gender: '女',
                salary: 12000, city: '北京', time: new Date().toLocaleString(),
            });
            stusData.push({
                id: globalNewStuId++, uname: 'red', age: 25, gender: '男',
                salary: 20000, city: '上海', time: new Date().toLocaleString(),
            });
            renderTableEl();
            localStorage.setItem('stus-data', JSON.stringify(stusData));
            localStorage.setItem('global-new-stu-id', globalNewStuId);
        });
    })();

    (function initStusData() {
        stusData = JSON.parse(localStorage.getItem('stus-data')) || [];
    })();

    (function initCreateRowBtnEl() {
        const unameInputEl = document.querySelector('input.uname');
        const ageInputEl = document.querySelector('input.age');
        const salaryInputEl = document.querySelector('input.salary');
        const genderSelectEl = document.querySelector('select#gender');
        const citySelectEl = document.querySelector('select#city');
        document.querySelector('form.create-row').addEventListener('submit', function (e) {
            e.preventDefault();
            if (!unameInputEl.value.trim() || !ageInputEl.value || !salaryInputEl.value) {
                return alert('输入内容不能为空！');
            }
            stusData.push({
                id: globalNewStuId++,
                uname: unameInputEl.value.trim(),
                age: ageInputEl.value,
                gender: genderSelectEl.value,
                salary: salaryInputEl.value,
                city: citySelectEl.value,
                time: new Date().toLocaleString(),
            });
            this.reset(); //重置表单
            renderTableEl(); //刷新表格
            //保存数据
            localStorage.setItem('stus-data', JSON.stringify(stusData));
            localStorage.setItem('global-new-stu-id', globalNewStuId);
        });
    })();

    (function initDeleteRowBtnEl() {
        tableBodyEl.addEventListener('click', function (e) {
            if (e.target.classList.contains('delete-row')) {
                const rowIndex = +e.target.dataset.index;
                if (!confirm(`确定删除这行吗？（学号：${stusData[rowIndex].id}）`))
                    return;
                stusData.splice(rowIndex, 1);
                renderTableEl();
                localStorage.setItem('stus-data', JSON.stringify(stusData));
            }
        });
    })();

    renderTableEl();

    function renderTableEl() {
        if (!stusData || stusData.length === 0) {
            tableBodyEl.innerHTML = '';
            rowCountEl.innerText = 0;
            return;
        }
        const rows = stusData.map((stu, index) => {
            return `<tr>
    <td>${stu.id}</td>
    <td>${stu.uname}</td>
    <td>${stu.age}</td>
    <td>${stu.gender}</td>
    <td>${stu.salary}</td>
    <td>${stu.city}</td>
    <td>${stu.time}</td>
    <td class="operations">
        <a class="delete-row" data-index="${index}"><i class="fa-solid fa-trash"></i>删除</a>
    </td>
</tr>`;
        });
        tableBodyEl.innerHTML = rows.join('\n');
        rowCountEl.innerText = rows.length;
    }
</script>
</body>
</html>